package com.example.gkcircle.library.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.util.Log;

import com.example.gkcircle.library.object.Book;
import com.example.gkcircle.library.object.DetailBook;
import com.example.gkcircle.library.object.GKUser;

/**
 * 
 * @ClassName: LibraryAnalysis
 * @Description: TODO(解析HTML工具类)
 * @author ZhouHua
 * @date 2015年9月5日 下午1:55:17
 *
 */
public class LibraryAnalysis {

	private static final int LIBRARY_TITLE = 24;
	private static final String BORROWABLE = "可借";
	private static final String UNBORROWABLE="非可借";

	// 判断是否被校园网拦截
	public static boolean isBeenStop(Document doc) {
		Elements trs = doc.select("table").select("tr");
		String title = doc.title().toString();
		if (title.trim().length() != LIBRARY_TITLE) {
			return true;
		}
		return false;
	}

	/**
	 * @Title: analysisSearchResult
	 * @Description: 解析搜索结果列表
	 * @param @param result
	 * @return List<Book>
	 */
	public static List<Book> analysisSearchResult(String result) {
		List<Book> bookList = new ArrayList<Book>();
		Document doc = Jsoup.parse(result);
		Elements trs = doc.select("table").select("tr");
		// 校园网拦截检测
		if (isBeenStop(doc)) {
			return null;
		}
		int i = 1;
		for (; i < trs.size(); i++) {
			Book book = new Book();
			Elements tds = trs.get(i).select("td");
			for (int j = 0; j < tds.size(); j++) {
				switch (j) {
				case 1:
					book.setUrl(tds.select("a[target=_blank]").attr("href"));
					book.setBookName(tds.get(j).text().toString());
					break;
				case 2:
					book.setAuthor(tds.get(j).text().toString());
					break;
				case 3:
					book.setPublish(tds.get(j).text().toString());
					break;
				case 4:
					book.setCallNumber(tds.get(j).text().toString());
					break;
				case 5:
					book.setType(tds.get(j).text().toString());
					break;
				default:
					break;
				}
			}
			bookList.add(book);
		}
		return bookList;
	}

	/**
	 * 
	 * @Title: analysisUserInfo
	 * @Description: (解析User信息)
	 * @param @param context
	 * @param @param userId
	 * @param @param password
	 * @param @param info
	 * @param @return GKUser
	 */
	public static GKUser analysisUserInfo(Context context, String userId, String password, Elements info) {
		GKUser user = new GKUser();
		user.setUserId(userId);
		user.setPassword(password);
		user.setEmail(LibraryStringUtil.FilerEmail(LibraryStringUtil.filerUserInfo(info.get(16).text().toString())));
		user.setVerifyEmail(LibraryStringUtil.getEmailStatus(LibraryStringUtil.filerUserInfo(info.get(16).text().toString())));
		user.setUserName(LibraryStringUtil.filerUserInfo(info.get(1).text().toString()));
		user.setDepartment(LibraryStringUtil.filerUserInfo(info.get(15).text().toString()));
		user.setGrade(getGrade(LibraryStringUtil.filerUserInfo(info.get(18).text().toString())));
		user.setPhone(LibraryStringUtil.filerUserInfo(info.get(25).text().toString()));
		user.setSex(LibraryStringUtil.filerUserInfo(info.get(21).text()).equals("男") ? true : false);
		GKUser.setCurrentUser(context, user);
		return user;
	}

	/**
	 * 解析详细图书信息
	 */
	public static DetailBook analysisDetailBookInfo(String result) {
		Document doc = Jsoup.parse(result);
		// ISBN
		String ISBN = doc.select("ul.sharing_zy").select("li").get(0).select("a[target=_blank]").attr("href");
		// marc信息
		Integer marc = Integer.valueOf(LibraryStringUtil.filerOnlyNumber(doc.select("p#marc").text()));

		Elements trs = doc.select("table").select("tr");
		DetailBook detailBook = new DetailBook();
		// 用于保存不可借图书的日期list
		List<String> unBorrowable = new ArrayList<String>();
		detailBook.setISBN(LibraryStringUtil.filerOnlyNumber(ISBN));
		detailBook.setViews(marc);
		int i = 1;
		for (; i < trs.size(); i++) {
			Elements tds = trs.get(i).select("td");
			for (int j = 0; j < tds.size(); j++) {
				switch (j) {
				case 3:
					if(isLocation(tds.get(j).text().toString())){
						detailBook.setLocation(tds.get(j).text().toString());
					}
					break;
				case 4:
					if(detailBook.getLocation()==null ||detailBook.getLocation().isEmpty()|| !isLocation(detailBook.getLocation())){
						break;
					}
					String status = tds.get(j).text().toString();
					Log.i("status:", status);
					// 是否有可借图书
					if (hasBorrowable(status)) {
						int count = detailBook.getStatus()!=null? Integer.parseInt(detailBook.getStatus()) : 0;
						detailBook.setStatus((count + borrowableCount(status)) + "");
					} else {
						if(status.equals(UNBORROWABLE)){
							break;
						}
						unBorrowable.add(filerDate(status));
					}
					break;
				case 5:
					if(detailBook.getLocation()==null ||detailBook.getLocation().isEmpty()|| !isLocation(detailBook.getLocation())){
						break;
					}
					detailBook.setReturnPos(tds.get(j).text().toString());
				break;
				default:
					break;
				}
			}
		}
		// 不为空则不可借
		// 需计算最近可该借书的时间
		if (!unBorrowable.isEmpty()) {
			String date=nearDate(unBorrowable);
			if(null==date)detailBook.setStatus("");
			else detailBook.setStatus("借出-应还日期：" + date);
			unBorrowable.clear();
			return detailBook;
		}
		detailBook.setStatus("可借" + "(" + detailBook.getStatus() + ")");
		return detailBook;
	}

	public static boolean isLocation(String location){
		if(location.equals("密集型书库") || location.equals("赠送书库")||location.equals("广州校区借书处")||location.equals("珠海校区采编部") ||location.isEmpty()){
              return false;
		}
		return true;
	}

	/**
	 * @Title: analysisJson
	 * @Description: TODO(解析详细图书的Json数据)
	 * @param @param jsonData
	 * @param @param detailBook
	 * @param @return 设定文件
	 * @return DetailBook 返回类型
	 * @throws
	 */
	public static DetailBook analysisJson(String json, DetailBook detailBook) {
		try {
			JSONObject jsonData = new JSONObject(json);
			detailBook.setIntro(jsonData.getString("summary"));
			detailBook.setCatalog(jsonData.getString("catalog"));
			List<String> tags = new ArrayList<String>();
			for (int i = 0; i < jsonData.getJSONArray("tags").length(); i++) {
				tags.add(jsonData.getJSONArray("tags").getJSONObject(i).getString("title"));
			}
			detailBook.setTag(tags);
			detailBook.setBigImgUrl(jsonData.getJSONObject("images").getString("large"));
			detailBook.setSmallImgUrl(jsonData.getJSONObject("images").getString("medium"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return detailBook;
	}

	public static boolean hasBorrowable(String status) {
		if (status.equals(BORROWABLE)) {
			return true;
		}
		return false;
	}

	public static int borrowableCount(String status) {
		int count = 0;
		if (status.equals(BORROWABLE)) {
			count = 1;
		}
		return count;
	}

	/**
	 * 
	 * 描述： 冒泡排序计算出最近应还书的时间
	 * 
	 *            []
	 * @return String
	 */
	public static String nearDate(List<String> date) {
		long[] m = new long[date.size()];
		String nd = null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date d;
		try {
			for (int i = 0; i < date.size(); i++) {
				d = df.parse((date.get(i).trim()));
				m[i] = d.getTime();
			}
			nd = df.format(new Date(max(m)));

		} catch (Exception e) {

		}
		return nd;
	}



	public static long max(long[] l){
		long max=0;
		for(int i=0;i<l.length;i++){
			if(l[i]>max){
				max=l[i];
			}
		}
		return max;
	}
	/**
	 * 
	 * 描述： 冒泡排序
	 * 
	 * @return long
	 */
	public static long BubbleSort(long[] l) {
		for (int i = 0; i < l.length; i++) {
			for (int j = i + 1; j <= l.length - 1; j++) {
				if (l[i] < l[j]) {
					long temp = l[i];
					l[i] = l[j];
					l[j] = temp;
				}
			}
		}
		return l[l.length - 1];
	}

	// 过滤不可借图书的冒号
	public static String filerDate(String date) {
		int s = date.trim().indexOf("：");
		date = date.substring(s + 1);
		return date;
	}

	public static String getGrade(String d){
		int index=d.indexOf("级");
		if(index==-1)return "";
		return d=d.substring(index-2,index)+d.substring(index+1)+"班";
	}

	public static List<Book> anlysisBorrowing(String document){
		Document hist = Jsoup.parse(document);
		Elements trs = hist.select("table.table_line").select("tr");
		Elements renew = hist.select("input[title=renew]");
		List<Book> bookList=new ArrayList<Book>();
		int firstRow = 1;
		for (; firstRow < trs.size(); firstRow++) {
			Book book =new Book();
			Elements tds = trs.get(firstRow).select("td");
			for (int table_cell = 0; table_cell < tds.size(); table_cell++) {
				switch (table_cell) {
					case 0:
						book.setBarCode(tds.get(table_cell).text());
						break;
					case 1:
						book.setBookName(getBookName(tds.get(table_cell).text().toString()));
						book.setAuthor(getAuthor(tds.get(table_cell).text().toString()));
						book.setUrl(tds.get(table_cell).select("a.blue").attr("href"));
						break;
					case 2:
						book.setBorrowedAt(getAuthor(tds.get(table_cell).text().toString()));
						break;
					case 3:
						book.setReturnAt(tds.get(table_cell).text().toString());
						break;
					case 7:
						book.setRenewCode(number(tds.get(table_cell).select("input[title=renew]").attr("onclick")));
						break;
				}
			}
			bookList.add(book);
		}
		return bookList;
	}

	public static List<Book> anlysisBorrowed(String document){
		Document hist = Jsoup.parse(document);
		Elements trs = hist.select("table.table_line").select("tr");
		List<Book> bookList=new ArrayList<Book>();
		int firstRow = 1;
		for (; firstRow < trs.size(); firstRow++) {
			Book book =new Book();
			Elements tds = trs.get(firstRow).select("td");
			for (int table_cell = 0; table_cell < tds.size(); table_cell++) {
				switch (table_cell) {
					case 2:
						book.setBookName(tds.get(table_cell).text().toString());
						book.setUrl(tds.get(table_cell).select("a.blue").attr("href"));
						break;
					case 3:
						book.setAuthor(tds.get(table_cell).text().toString());
						break;
					case 4:
						book.setBorrowedAt(tds.get(table_cell).text().toString());
						break;
					case 5:
						book.setReturnAt(tds.get(table_cell).text().toString());
						break;
				}
			}
			bookList.add(book);
		}
		return bookList;
	}


	public static String getBookName(String s) {
		int p = s.indexOf("/");
		s = s.substring(0, p);
		return s;
	}

	public static String getAuthor(String s) {
		int p = s.indexOf("/");
		s = s.substring(p + 1);
		return s;
	}

	public static String number(String text) {
		int s = text.indexOf(",");
		int e = text.lastIndexOf(",");
		text = text.substring(s + 2, e - 1);
		return text;
	}
}
